/**
 *
 */
package de.sendorian.app.forumArchive.download;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.annotation.Nonnull;

import org.apache.log4j.Logger;

import de.sendorian.app.forumArchive.domain.Image;
import de.sendorian.app.forumArchive.domain.Topic;
import de.sendorian.util.CollectionUtils;

class ImageDownloaderTask implements Runnable {

	private static final Logger logger = Logger.getLogger(ImageDownloaderTask.class);

	Image image;
	Topic topic;
	Set<String> downloadedFiles;
	List<String> filesInArchives;

	ImageDownloaderTask(@Nonnull Image image, @Nonnull final Topic topic,
	    @Nonnull Set<String> downloadedFiles, @Nonnull List<String> filesInArchives) {
		this.image = image;
		this.topic = topic;
		this.downloadedFiles = downloadedFiles;
		this.filesInArchives = filesInArchives;
	}


	public void run() {
		try {
			if (!CollectionUtils.containsIgnoreCase(image.getName(), filesInArchives)) {
				boolean downloaded = image.save();
				downloadedFiles.add(image.getName());
				if (downloaded) {
					logger.info("Downloaded " + image.getName() + " from topic \""
					    + topic.getName() + "\"");
				}
			}
		} catch (IOException e) {
			logger.error("Could not save image \"" + image.getUrl()
			    + "\" in topic  \"" + topic.getName() + "\" (" + topic.getUrl() + ")", e);
		}
	}
}